package com.bootdo.sz.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bootdo.common.utils.BDSeqUtils;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.UserService;
import com.bootdo.sz.dao.BdDao;
import com.bootdo.sz.dao.SeqDao;
import com.bootdo.sz.domain.BDSumDO;
import com.bootdo.sz.domain.BdDO;
import com.bootdo.sz.domain.SeqDO;
import com.bootdo.sz.service.BdService;



@Service
public class BdServiceImpl implements BdService {
	@Autowired
	private BdDao bdDao;
	@Autowired
	private SeqDao seqDao;
	@Autowired
	private UserService userService;
	
	@Override
	public BdDO get(Long id){
		return bdDao.get(id);
	}
	
	@Override
	public List<BdDO> list(Map<String, Object> map){
		return bdDao.list(map);
	}
	
	@Override
	public int count(Map<String, Object> map){
		return bdDao.count(map);
	}
	
	@Override
	public int save(BdDO bd){
		return bdDao.save(bd);
	}
	
	@Override
	public int update(BdDO bd){
		return bdDao.update(bd);
	}
	
	@Override
	public int remove(Long id){
		return bdDao.remove(id);
	}
	
	@Override
	public int batchRemove(Long[] ids){
		return bdDao.batchRemove(ids);
	}

	@Override
	@Transactional
	public synchronized int saveBd(BdDO bd) {
		SeqDO seqDO = seqDao.get(1L);
		Long seq = seqDO.getBdNo();
		String bdNo = BDSeqUtils.getBDSeq(++seq);
		seqDO.setBdNo(seq);
		seqDao.update(seqDO);
		bd.setStatus("0"); // 正常
		bd.setBdNo(bdNo);
		bd.setCreateDate(new Date());
		UserDO user = ShiroUtils.getUser();
		bd.setCreateBy(user.getName());
		Long userId = ShiroUtils.getUserId();
		List<Long> userRole = userService.getUserRole(userId);
		Long roleId = userRole.get(0);
		if(roleId == 62) {
			bd.setUserId(ShiroUtils.getUserId());
		}
		bd.setBdEndDate(DateUtils.getBdEndDate(bd.getBdStartDate(), Integer.valueOf(bd.getBdValid())));
		bdDao.save(bd);
		// 修改可创建的保单数量
		if(roleId == 61) {
			// 代理商
			userService.updateBDQua(userId);
		} else if(roleId == 60) {
			// 一级管理员
			Long fsUserId = bd.getUserId();
			UserDO userDO = userService.get(fsUserId);
			userService.updateBDQua(Long.valueOf(userDO.getBelongProxy()));
		} else if(roleId == 62) {
			// 4s
			UserDO userDO = userService.get(userId);
			userService.updateBDQua(Long.valueOf(userDO.getBelongProxy()));
		}
		return 1;
	}

	@Override
	public BdDO getBD(String productNo, String vinCode) {
		return bdDao.getBD(productNo, vinCode);
	}

	@Override
	public List<BDSumDO> bdSumList(Map<String, Object> params) {
		return bdDao.bdSumList(params);
	}

	@Override
	public BDSumDO bdSum(Map<String, Object> params) {
		return bdDao.bdSum(params);
	}
	
}
